<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { addArticle } from '@/utils/api'
const emit = defineEmits(['closeo',])
const imageUrl = ref('');
const content = ref('');
const iscontent = ref(false);
const ruleForm = ref(null);

const rules = reactive({
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
        { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
    ],
    author: [
        { required: true, message: '请输入作者', trigger: 'blur' },
        { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
    ],
    digest: [
        { required: true, message: '请输入摘要', trigger: 'blur' },
        { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
    ],
    fengmian: [{ required: true, }]
})

const editorOption = {
    modules: {
        toolbar: [
            ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
            ['blockquote', 'code-block'],
            [{ 'header': 1 }, { 'header': 2 }],               // custom button values
            [{ 'list': 'ordered' }, { 'list': 'bullet' }],
            [{ 'script': 'sub' }, { 'script': 'super' }],      // superscript/subscript
            [{ 'indent': '-1' }, { 'indent': '+1' }],          // outdent/indent
            [{ 'direction': 'rtl' }],                         // text direction
            [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
            [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
            [{ 'font': [] }],
            [{ 'align': [] }],
            ['image',]//去除video即可
        ],
    }
};

const editorBlur = (e) => {
    console.log(e);
    console.log(content.value);
}

const upd = ref({
    action: '/api/smtWechat/uploadArticleImage',
    data: {
        id: '',
        type: '园区动态',
        areaId: '0000147'
    }
})

const handleAvatarSuccess = (res, file) => {
    if (res.code == '200') {
        imageUrl.value = URL.createObjectURL(file.raw);
    } else {
        ElMessage({
            message: res.message,
            type: 'warning',
        })

    }

};
const beforeAvatarUpload = (file) => {
    const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isJPG) {
        ElMessage({
            message: '只接受图片!',
            type: 'warning',
        })
    }
    if (!isLt2M) {
        ElMessage({
            message: '上传图片大小不能超过 2MB!',
            type: 'warning',
        })
    }
    return isJPG && isLt2M;
};

const submitForm = async (formName) => {
    if (!formName) return
    await formName.validate((valid, fields) => {
        if (valid) {
            if (imageUrl.value == '' || imageUrl.value == null) {
                ElMessage({
                    message: '封面不能为空',
                    type: 'warning',
                })
                return
            }
            if (content.value == null || content.value == '') {
                ElMessage({
                    message: '内容不能为空',
                    type: 'warning',
                })
                return
            }

            function addImageStyles(htmlString, styles) {
                // 使用正则表达式匹配所有 <img> 标签
                return htmlString.replace(/<img([^>]+)>/g, function (match, p1) {
                    // 为每个 <img> 标签添加内联样式
                    return `<img${p1} style="${styles}">`;
                });
            }

            // 示例：将图片宽度设置为300px，高度自动调整
            const updatedHtml = addImageStyles(content.value, 'width: 300px; height: auto;');


            const dataMse = props.msg;
            let obj = {
                "id": dataMse.id, //文章唯一ID
                "areaId": dataMse.areaId, //保护区ID
                "title": dataMse.title, //标题
                "author": dataMse.author, //作者
                "groupType": '园区动态', //分组名称
                "content": updatedHtml, //内容
                "digest": dataMse.digest //摘要
            };

            addArticle(obj).then(res => {
                if (res.code == '200') {
                    ElMessage({
                        message: '保存成功',
                        type: 'success',
                    })
                    emit('closeo', '');
                } else {
                    ElMessage({
                        message: res.messge,
                        type: 'warning',
                    })
                }
            })
            // /*  (async function f() {
            //      let res = await vm.$api.http.post(vm.$api.api.addArticle, obj)
            //      if (res.data.code == '200') {
            //          vm.$parent.qingchuobj();
            //          vm.$parent.close();
            //          vm.success('成功');
            //          vm.$parent.getpage();
            //      } else {
            //          vm.warning(res.data.messge);
            //      }
            //  })() */

            // emit('closeo', PopupObj);

        } else {
            console.log('error submit!!', fields);
            return false;
        }
    });
};

let props = defineProps({
    msg: {
        type: Object,
        default: () => []
    }
});

onMounted(() => {
    upd.value.data.id = props.msg.id;
    imageUrl.value = props.msg.coverPicture;
    content.value = JSON.parse(JSON.stringify(props.msg.content));
    iscontent.value = true

})

</script>
<template>
    <div class="son">
        <div class="title">
            <span>园区动态</span>
            <!-- @click.stop="colse" -->
            <el-button type="primary" @click.stop="emit('closeo', '')">返回</el-button>
        </div>

        <div class="neirong">
            <div style="flex: 7;margin-right: .1rem;">
                <el-form :model="msg" :rules="rules" ref="ruleForm" size="large" label-width="100px"
                    class="demo-ruleForm" style="padding-right: 20px;">
                    <el-form-item label="标题" prop="title">
                        <el-input v-model="msg.title"></el-input>
                    </el-form-item>

                    <el-form-item label="作者" prop="author">
                        <el-input v-model="msg.author"></el-input>
                    </el-form-item>

                    <el-form-item label="摘要" prop="digest">
                        <el-input v-model="msg.digest"></el-input>
                    </el-form-item>
                    <!--        封面 B -->
                    <el-form-item label="封面">
                        <el-row>
                            <el-col :span="24"><span style="color: #999999">支持png、jpg格式，建议大小231px*212px</span></el-col>
                        </el-row>
                    </el-form-item>


                    <el-form-item label="">
                        <el-upload class="avatar-uploader" :action="upd.action" :data="upd.data" :show-file-list="false"
                            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                            <img v-if="imageUrl != ''" :src="imageUrl" class="avatar">
                            <el-icon style="width: 178px;height: 178px;" v-else
                                class="el-icon-plus avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                    <!--        封面 E -->

                    <el-form-item label="内容">
                        <el-row>
                            <el-col :span="24"><span style="color: #999999">（使用富文本编辑文章内容）</span></el-col>
                        </el-row>
                    </el-form-item>


                    <!-- <el-form-item label=""> -->
                    <div v-if="iscontent" style="margin-left: 100px;margin-bottom: 30px;">
                        <quill-editor content-type='html' v-model:content='content' :options='editorOption' />
                    </div>

                    <!-- </el-form-item> -->

                    <el-form-item>
                        <el-button type="primary" @click="submitForm(ruleForm)">保存</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div style="flex: 3;margin-right: .1rem;">
                <div>
                    <span style="font-size: 16px;text-indent: 1em;">预览</span>
                </div>
                <div>
                    <div style="margin-bottom: 12px;margin-top: 24px;padding: 0 10px;text-align: center">
                        <span style="font-size: 18px;">{{ msg.title }}</span>
                    </div>
                    <div style="margin-bottom: 12px;padding: 0 10px;text-align: center">
                        <span style="color: #666666;font-size: 16px;">{{ msg.digest }}</span>
                    </div>
                    <div class="ql-editor" style="height:calc(100% - 1.5rem);padding: 0 10px;text-indent: 1em;"
                        v-html="content">
                    </div>

                </div>
            </div>
        </div>

    </div>
</template>
<style scoped>
.son {
    width: 100%;
    height: 100%;
    background-color: #fff;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2;
}

.title {
    width: 100%;
    height: .6rem;
    padding: 0 .16rem;
    border-bottom: 1px solid #eee;
    font-weight: 700;
    font-size: .18rem;
    display: flex;
    align-items: center;
    justify-content: space-between;
    overflow: hidden;
    box-sizing: border-box;
}

.neirong {
    width: 100%;
    height: calc(100% - .8rem);
    padding-top: .16rem;
    display: flex;
    flex-shrink: 0;
    overflow: hidden;
}

.neirong>div {
    /*width: 100%;*/
    height: 100%;
    overflow-x: hidden;
    overflow-y: auto;
}

.neirong>div:nth-child(2) {
    background-color: #E6E5E5;
}


.neirong>div:nth-child(2)>div:nth-child(1) {
    width: 100%;
    height: .5rem;
    background-color: #fff;

}

.neirong>div:nth-child(2)>div:nth-child(2) {
    width: calc(100% - 1rem);
    height: calc(100% - .9rem);
    margin: .2rem auto;
    background-color: #fff;
    overflow: hidden;
}
</style>
